/**
 * PHOSIDE: PHosphorylation Site IDentification Engine.
 * Copyright 2009 Digital Biology Lab, University of Missouri.
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version. <p/> This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more
 * details.
 */

package phoside.disorder;

import phoside.io.fasta.parser.DefaultHeaderParser;
import phoside.io.fasta.parser.HeaderParser;
import phoside.io.fasta.parser.HeaderRule;
import phoside.io.fasta.util.FastaVisitor;

import phoside.util.StaticFinalValues;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * @author gjj
 */
public class DisorderReaderFastaVisitor implements FastaVisitor {

    private final Map<String,List<Double>> mapAccDisorder;
    private final HeaderParser headParser;

    public DisorderReaderFastaVisitor(final Map<String,List<Double>> mapAccDisorder,
                                      final HeaderRule headRule) {
        if (mapAccDisorder==null || headRule==null) {
            throw new NullPointerException();
        }

        this.mapAccDisorder = mapAccDisorder;
        headParser = new DefaultHeaderParser(headRule);
    }

    /**
     * 
     * @param header
     * @param sequence
     */
    public void visit(final String header, final String sequence) {
        if (header==null || sequence==null) {
            throw new NullPointerException("Null header or sequence.");
        }

        headParser.parse(header);
        String accession = headParser.getAccession();
        if (accession != null) {
            List<Double> res = parseSequence(sequence);
            if (res != null) {
                mapAccDisorder.put(accession, res);
            }
        }
    }

    private List<Double> parseSequence(final String sequence) {
        String[] strs = sequence.split(StaticFinalValues.SEPARATOR);
        int n = strs.length;

        List<Double> res = new ArrayList<Double>(n);
        try {
            for (String str : strs) {
                res.add(Double.parseDouble(str));
            }
            return res;
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
            return null;
        }
    }

}
